"use strict";
import * as React from 'react';
import { autoSize, commonStyles } from "../assets/styles/common";
import MyIcon from "./icon";
import { SCREEN_WIDTH } from "../constant";
import MyImagePicker from "./MyImagePicker";
import MyText from "./MyText";
import Colors from "../assets/styles/Colors";
import T from "../utils/T";
const { View, FlatList, TouchableOpacity, Image, CameraRoll, Alert, ActivityIndicator } = require('react-native');
const { connect } = require('react-redux');
class MyGallery extends React.Component {
    constructor(props, context) {
        super(props, context);
        this.getPhotos = (params) => {
            return new Promise((resolve, reject) => {
                CameraRoll.getPhotos(Object.assign({}, params)).then((data) => {
                    resolve({ images: data.edges, page_info: data.page_info });
                }).catch((e) => {
                    this._images = [1];
                    Alert.alert('当前暂无相册权限', '无法获取相册信息，请前往设置->隐私->照片->火星空间 打开相册权限', [
                        { text: '确定' },
                        { text: '取消' },
                    ]);
                });
            });
        };
        this.onEndReached = () => {
            if (!this.state.page_info || !this.state.page_info.has_next_page || this.state.loading) {
                return;
            }
            this.getPhotos({
                first: 9,
                assetType: 'Photos',
                groupTypes: 'All',
                after: this.state.page_info.end_cursor
            }).then(({ images, page_info }) => {
                if (this._loadedPage.indexOf(page_info.end_cursor) === -1) {
                    let image = this.state.images;
                    this._loadedPage.push(page_info.end_cursor);
                    if (page_info.has_next_page && page_info.end_cursor !== this.state.end_cursor) {
                        image = image.concat(images);
                        this.setState({
                            images: image,
                            page_info,
                            loading: false,
                            tip: page_info.has_next_page ? T('loading') + '...' : T('no more data') + '...'
                        });
                    }
                    else {
                        this.setState({
                            page_info: null,
                            tip: T('no more data')
                        });
                    }
                }
                else {
                    this.setState({
                        page_info: null,
                        loading: false,
                        tip: T('no more data')
                    });
                }
            });
            this.setState({ loading: true });
        };
        this.renderItem = ({ item, index }) => {
            if (index === 0) {
                return (<TouchableOpacity style={[commonStyles.centerVH, Object.assign({}, this._itemSize)]} activeOpacity={1} onPress={this.cameraPress.bind(this)}>
                    <MyIcon name='icon-icon-camera-copy' color='#DAC229' size={40}/>
                </TouchableOpacity>);
            }
            return (<TouchableOpacity style={[commonStyles.centerVH, Object.assign({}, this._itemSize)]} activeOpacity={1} onPress={this.imageItemPress.bind(this, item.node)}>
                <Image source={{ uri: item.node.image.uri }} style={{ width: '100%', height: '100%' }}/>
            </TouchableOpacity>);
        };
        this.renderLoading = () => {
            return (<View style={[commonStyles.flex1, commonStyles.centerVH]}>
                <ActivityIndicator animated={!this.state.images || this.state.images.length <= 0} size={'small'} color={Colors.Active}/>
                <MyText color={Colors.Active}>{T('loading') + '...'}</MyText>
            </View>);
        };
        this.renderListFooterComponent = () => {
            return (<View style={[commonStyles.flexRow, commonStyles.centerVH, { width: SCREEN_WIDTH, height: autoSize(60) }]}>
                <ActivityIndicator animated={this.state.loading} hidesWhenStopped color={Colors.Active} size={'small'}/>
                <MyText style={{ marginLeft: 10 }} color={Colors.Active}>{this.state.tip}{`共${this.state.images ? this.state.images.length : 0}张`}</MyText>
            </View>);
        };
        this.state = {
            images: null,
            loading: false,
            tip: T('loading') + '...',
            page_info: {
                start_cursor: null,
                end_cursor: null,
                has_next_page: false,
            }
        };
        this._loadedPage = [];
        this._itemSize = { width: SCREEN_WIDTH / 3, height: SCREEN_WIDTH / 3 };
    }
    componentDidMount() {
        this.getPhotos({
            first: 8,
            assetType: 'Photos',
            groupTypes: 'All'
        }).then(({ images, page_info }) => {
            this.setState({ images: [1].concat(images), page_info });
        });
    }
    imageItemPress(image) {
        this.props.onSelectedImage && this.props.onSelectedImage(image);
    }
    cameraPress() {
        MyImagePicker.launchCamera({}, (res) => {
            if (res.error) {
                Alert.alert('当前暂无相机权限', '无法获取相册信息，请前往设置->隐私->相机->火星空间 打开相机权限', [
                    { text: '确定' },
                    { text: '取消' },
                ]);
            }
            else {
                this.props.onSelectedImage && this.props.onSelectedImage({ image: res });
            }
        });
    }
    render() {
        let images = [];
        if (this.state.images) {
            this.state.images.map((i) => {
                if (images.indexOf(i) === -1) {
                    images.push(i);
                }
            });
        }
        return (<View {...this.props}>
                {this.state.images ? <FlatList data={images} extraData={this.state} style={{ flex: 1 }} numColumns={3} onEndReachedThreshold={1} onEndReached={this.onEndReached} ListFooterComponent={this.renderListFooterComponent} renderItem={this.renderItem.bind(this)} keyExtractor={(item, index) => index}/> : this.renderLoading()}
            </View>);
    }
}
MyGallery.defaultProps = {
    onSelectedImage: null
};
export default MyGallery;
